# !/usr/bin/env python
# -*- coding: utf-8 -*-
import shutil, datetime, os, re, time
from utils.user_wincommand import WinCommand
from utils.config_mgr import ConfigMgr
from utils.user_logbook import user_log as logger
from utils.datetime_func import now_time_str, now_day_time
from utils.user_compress import MyZip


def get_week():
    now_dt = datetime.datetime.now().weekday()
    if now_dt == 6:
        return "星期天"
    elif now_dt == 0:
        return "星期一"
    elif now_dt == 1:
        return "星期二"
    elif now_dt == 2:
        return "星期三"
    elif now_dt == 3:
        return "星期四"
    elif now_dt == 4:
        return "星期五"
    elif now_dt == 5:
        return "星期六"

def RemoveOld(BackupInfo):
    KeepsDay = BackupInfo["KeepDays"]  # 数据库备份保留天数
    BackupDir = BackupInfo["BackupDir"]
    FileList = os.listdir(BackupDir)
    FileNum = list()
    for File in FileList:
        if len(File) == 8:
            check = re.match(r'^20[2-9][0-9][0-9][0-9][0-9][0-9]', File)
            if check:
                filename = check.group()
                FileNum.append(int(filename))
        else:
            logger.warning("备份文件命名不规范")
    while len(FileNum) > KeepsDay:
        index = min(FileNum)
        for dt in FileList:
            if str(index) == dt:
                FileNum.remove(index)
                shutil.rmtree(BackupDir + "\\" + dt)
                logger.info("{}---备份目录删除成功！".format(dt))

def ExecuteWork(command, zipfile, FileList, SqlName, DbName):
    cmd = WinCommand()
    cmd.Commands(command)
    logger.info("备份文件[{}]已生成...".format(DbName))
    zipfile.compress(FileList, SqlName + ".zip")
    logger.info(("备份文件[{}]压缩成功...".format(DbName)))



def BackWork(BackupInfo, MysqlDB):
    BaseDir = BackupInfo["BaseDir"]
    user = MysqlDB["user"]  # 数据库用户名
    passwd = MysqlDB["password"]  # 数据库密码
    DbList = BackupInfo["DbList"]  # 需要备份的数据库列表
    BackupDir = BackupInfo["BackupDir"]  # 数据库备份文件存储目录E:\BACKUPS
    BackDataDir = BackupDir + "\\" + now_day_time()   #E:\BACKUPS\20201216
    isExists = os.path.exists(BackDataDir)
    FileList = list()
    SQL_rm = list()
    if not isExists:
        os.makedirs(BackDataDir)
        logger.info("备份目录创建成功！")
        zipfile = MyZip()
        for DB in DbList:
            SqlName = BackDataDir + "\\" + now_day_time() + "_" + DB + ".sql"
            command = BaseDir + "\\mysqldump.exe -u" + user + " -p" + passwd + \
                      " " + DB + " > " + SqlName
            DbName = now_day_time() + "_" + DB + ".sql"
            FileList.append(SqlName)
            ExecuteWork(command, zipfile, FileList, SqlName, DbName)
            SQL_rm.append(SqlName)
            FileList.clear()
        for i in range(len(SQL_rm)):
            os.remove(SQL_rm[i])
            logger.info("备份文件[{}]清除成功，保留其压缩文件！".format(SQL_rm[i].replace(BackDataDir + "\\", "")))
        RemoveOld(BackupInfo)
    else:
        logger.warning("{}的目录已生成备份文件夹...".format(BackDataDir))

def CheckingTime():
    BackupInfo = ConfigMgr.get("BackInfo")
    MysqlDB = ConfigMgr.get("MysqlDB")
    BackupTime = BackupInfo["BackupTime"]  # 数据库备份时间
    BackupFrequency = BackupInfo["BackupFrequency"]  # 数据库备份频率
    logger.info("初始化配置参数完成...")
    count = 0
    while True:
        if now_time_str()[-8:][:-3] == BackupTime[:-3]:
            if 10 <= abs(int(BackupTime[-2:]) - int(now_time_str()[-2:])) <= 20:
                if get_week() in BackupFrequency:
                    try:
                        BackWork(BackupInfo, MysqlDB)
                        time.sleep(30)
                    except Exception as e:
                        logger.error(repr(e))
        else:
            if count % 60 == 0:
                logger.info("Backup Server is running....")
                count = 0
            time.sleep(1)
            count += 1

def main():
    logger.info("自动备份工具V1.1版")
    logger.info("正在读取配置参数...")
    CheckingTime()



if __name__ == '__main__':
    main()